﻿using System;
using System.Windows.Forms;
using QAToolsAddin.Components;

namespace QAToolsAddin.GenericDialogs.Fields {

    public class FieldNumber : Field, IField {
        readonly ExcelRefEdit _control;
        readonly double _minValue;
        readonly double _maxValue;

        public override event EventHandler KeyReturn {
            add { _control.KeyReturn += delegate { value.Invoke(this, null); }; }
            remove { _control.KeyReturn += delegate { value.Invoke(this, null); }; }
        }

        public FieldNumber(string name, string info, double? value)
            : this(name, info, value, double.MinValue, double.MaxValue, false) { }

        public FieldNumber(string name, string info, double? value, bool retore)
            : this(name, info, value, double.MinValue, double.MaxValue, retore) { }

        public FieldNumber(string name, string info, double? value, double minValue, bool retore)
            : this(name, info, value, minValue, double.MaxValue, retore) { }

        public FieldNumber(string name, string info, double? value, double minValue, double maxValue = double.MaxValue, bool retore = false)
            : base(name, info, retore) {
            _minValue = minValue;
            _maxValue = maxValue;
            _control = new ExcelRefEdit {
                AllowTextInput = true,
                DisplayMode = ExcelRefEdit.XlMode.ValueNumber,
                MinNumber = minValue,
                MaxNumber = maxValue,
                Value = value
            };
        }

        public override Control Control {
            get { return _control; }
        }

        public double? Value {
            get { return (double?)_control.Value; }
            set { _control.Value = value; }
        }

        object IField.Value {
            get { return Value; }
            set { Value = (double?)value; }
        }

        public override bool Validate(out string errorMessage) {
            errorMessage = null;
            var number = (double?)_control.Value;
            if (number == null)
                return true;
            else if (number > _maxValue)
                errorMessage = "Number has to be inferior to " + _maxValue;
            else if (number < _minValue)
                errorMessage = "Number has to be superior to " + _minValue;
            else
                return true;
            _control.SelectAll();
            return false;
        }

    }

}